package org.levi.netty;

import com.alibaba.fastjson.JSONObject;
import com.sun.xml.internal.fastinfoset.Encoder;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.levi.core.RpcRequest;
import org.levi.netty.service.HelloServiceImpl;

import java.lang.reflect.Method;

/**
 * @author DevCenter
 */
public class MyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("channel is connected");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server:receive from client............");

        if (msg instanceof ByteBuf) {
            ByteBuf byteBuf = (ByteBuf) msg;
            byte[] bytes = new byte[byteBuf.capacity()];
            for (int i = 0; i < byteBuf.capacity(); i++) {
                bytes[i] = byteBuf.getByte(i);
            }
            String requestJson = new String(bytes, Encoder.UTF_8);
            System.out.println(requestJson);
            RpcRequest rpcRequest = JSONObject.parseObject(requestJson, RpcRequest.class);
            //获取class对象，通过反射实例化一个对象
            if ("org.levi.service.HelloService".equalsIgnoreCase(rpcRequest.getClassName())) {
                HelloServiceImpl helloService = new HelloServiceImpl();
                Class clazz = helloService.getClass();
                Method[] methods = clazz.getMethods();
                for (int j = 0; j < methods.length; j++) {
                    if (methods[j].getName().equals(rpcRequest.getMethodName())) {
                        Method method = methods[j];
                        //暂不判断参数，直接调用
                        method.invoke(helloService, rpcRequest.getParameters());
                    }
                }
            }
        }
        //RpcRequest rpcRequest = (RpcRequest) msg;
        ctx.writeAndFlush("success");
    }


}
